<?php

/**
 * 案件调解
 * @author HelloWorld
 * 2023-8-8
 * UTF-8
 */
class RepairsubmitController extends Controller_Base
{
    //案件分配记录列表
    public function IndexAction()
    {
        $request = $this->getRequest();
        $page = intval($request->getQuery('page', 1));
        $limit = intval($request->getQuery('limit', 50));
        $search = $request->getQuery('search', []);
        $is_show = intval($request->getQuery('is_show', 0));

        $is_search = 0;
        if ($search) {
            $page = $page ? $page : 1;
            $start = ($page - 1) * $limit;
            $where = $this->getWhere();
            array_push($where, "sysStatus = 1 and caseStatus <> 'close_case'");
            //欠款总额特殊处理
            $startdebtTotal = $search['startdebtTotal'];
            $startdebtAmount = $search['startdebtAmount'];
            $enddebtTotal = $search['enddebtTotal'];
            $enddebtAmount = $search['enddebtAmount'];
            unset($search['startdebtTotal']);
            unset($search['startdebtAmount']);
            unset($search['enddebtTotal']);
            unset($search['enddebtAmount']);
            foreach ($search as $key => $val){
                if(!empty($val)) {
                    if (strpos($key, 'Time') !== false || strpos($key, 'Date') !== false) {
                        $arr = explode(" 到", $val);
                        $begin = strtotime($arr[0]);
                        $end = strtotime($arr[1]) + 86400;
                        array_push($where, "$key >= $begin AND $key < $end");
                    } elseif (strpos($key, 'start') !== false && is_numeric($val)) {
                        array_push($where, str_replace('start', '', $key) . " >= {$val}");
                    } elseif (strpos($key, 'end') !== false && is_numeric($val)) {
                        array_push($where, str_replace('end', '', $key) . " < {$val}");
                    } elseif(in_array($key,['litigantName','cardId','telephone'])){
                        $caseId = $this->getCaseIdByLitigantName($val,$key);
                        array_push($where,"id in ({$caseId})");
                    } else {
                        if (is_numeric($val)) {
                            array_push($where, "{$key} = {$val}");
                        } else {
                            array_push($where, "{$key} = '{$val}'");
                        }
                    }
                    $is_search = 1;
                }
            }
            $having = '';
            if($startdebtTotal){
                $is_search = 1;
                $having .= "debtTotal >= {$startdebtTotal}";
                $search['startdebtTotal'] = $startdebtTotal;
            }
            if($enddebtTotal){
                $is_search = 1;
                $having = $having ? $having." and debtTotal <= {$enddebtTotal}" : " debtTotal <= {$enddebtTotal}";
                $search['enddebtTotal'] = $enddebtTotal;
            }
            if($startdebtAmount){
                $is_search = 1;
                $having .= "debtAmount >= {$startdebtAmount}";
                $search['startdebtAmount'] = $startdebtAmount;
            }
            if($enddebtAmount){
                $is_search = 1;
                $having = $having ? $having." and debtAmount <= {$enddebtAmount}" : " debtAmount <= {$enddebtAmount}";
                $search['enddebtAmount'] = $enddebtAmount;
            }
            if(!$is_search){
                echo '<script>alert("必须填写查询条件");window.location.href="/repairsubmit";</script>';
                die;
            }
            $seacher = array(
                'where' => $where,
                'limit' => $limit,
                'start' => $start,
                'order' => '`id` ASC',
                'group' => 'cardId',
                'having' => $having,
            );
            $cases = Module_Mediate_Case::getInstance()->getAllBySearch(['id,litigantName,cardId','sum(debtTotal) as debtTotal','sum(debtAmount) as debtAmount','count(id) as caseNum','max(overdueMonth) as overdueMonth'], $seacher, true);
            $total = Module_Mediate_Case::getInstance()->getGroupTotalBySearch(array("sum(debtTotal) as debtTotal",'sum(debtAmount) as debtAmount',), array('where' => $where,'group' => 'cardId', 'having' => $having,), true);
            $total = $total[0]['num'];
            $totalPage = ceil($total / $limit);

        }
        $query['limit'] = $limit;
        $query['search'] = $search;

        //赋值调解部门
        $this ->getMediationOrgan();
        //赋值调解员
        $this ->getMediator(1);
        //赋值资产方
        $this ->getAssets();
        SmartyAdapter::assign('arrList', empty($cases) ? [] : $cases);
        SmartyAdapter::assign('totalPage', empty($totalPage) ? 0 : $totalPage);
        SmartyAdapter::assign('totalnum',  empty($total) ? 0 : $total);
        SmartyAdapter::assign('pagesize', $limit);
        SmartyAdapter::assign('curPageNum', $page);
        SmartyAdapter::assign('query', $query);
        SmartyAdapter::assign('is_show', $is_show);
        SmartyAdapter::assign('customLabel', Module_Mediate_Case::$customLabel);
        SmartyAdapter::assign('customGrade', Module_Mediate_Case::$customGrade);
        SmartyAdapter::assign('mediateResult', Module_Mediate_Case::$mediateResult);
        SmartyAdapter::assign('page_query', http_build_query($query));
        SmartyAdapter::assign('batchName', 'XF'.date("Ymd"));


    }
    //生成批次，异步生成批次记录
    public function submitAction()
    {
        $dataId = $this->_request->getPost('case_id', 0);
        $repairType = $this->_request->getPost('repair_type', 0);
        $batchName = $this->_request->getPost('batch_name', '');
        if (!$dataId || !in_array($repairType,[1,2])) {
            AjaxTool::returnJsonData(4005);
        }
        if (!$batchName) {
            AjaxTool::returnJsonData(4003,'请输入批次名称');
        }
        if($repairType == 1 && date("d") >= 27){
            AjaxTool::returnJsonData(4003,'移动渠道每月27日后不允许提交修复');
        }
        $md5_data = md5($dataId.$repairType);
        $data_exists = Lib_Redis_Hash::hexists($this->admin['id'],$md5_data);
        if($data_exists){
            AjaxTool::returnJsonData(4000,'请勿重复提交，当前数据今日已提交');
        }else{
            $str_time = strtotime(date('Y-m-d 23:59:59'));
            Lib_Redis_Hash::hset($this->admin['id'],$md5_data,$md5_data);
            Lib_Redis_Hash::expireAt($this->admin['id'],$str_time);
        }
        $id_arr = explode(',', $dataId);
        if($repairType == 2 && count($id_arr) > 500){
            AjaxTool::returnJsonData(4003,'联通渠道单次提交不超过500');
        }
        $batchId = Module_Repair_RepairBatch::getInstance()->singleInsert(
            [
                'repairType' => $repairType,
                'repairNum' => count($id_arr),
                'repairStatus' => 1,
                'mediationOrganId' => $this->admin['mediationOrganId'],
                'creatId' => $this->admin['id'],
                'creatName' => $this->admin['name'],
                'batchName' => $batchName,
                'creatTime' => time(),
            ]
        );
        if(!$batchId){
            AjaxTool::returnJsonData('5000','批次创建失败');
        }
        if($batchId){
            foreach ($id_arr as $id){
                $data = [
                    'caseId' => $id,
                    'batchId' => $batchId,
                    'repairType' => $repairType,
                    'mediationOrganId' => $this->admin['mediationOrganId'],
                    'creatId' => $this->admin['id'],
                ];
                $post_data = [
                    'type' => 'Module_Task_Repair',
                    'method' => 'submitRepair',
                    'data' => $data
                ];
                @Module_Queue_Base::addQueue($post_data,1,2);
            }
        }
        AjaxTool::returnJsonData(200);
    }
}
